import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Image,
    ListView,
    Modal,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../res/styles/StyleUtils";
import I18n from "../../res/language/i18n";
import ViewUtils from "../../utils/ViewUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE, SynpaysTeken} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";

let ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
});
export default class SelectBankCardModal extends Component {
    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.bankCard = [];


        this.state = {
            visible: this.props.visible,
            refreshing: false,
            userId: this.props.userId,
            balance: 0,
            isFirstLoading: true,
            dataSource: ds,
            currency: 0,

            selectIndex: -1,
        };
    }


    onLoadData(userId) {
        this.bankCard = [];
        //  this.getDebitCardInfo(userId);
        this.getCreditCardInfo(userId);
        this.setState({
            refreshing: true,
        });

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'Wallet?', 'UserID=' + userId, SynpaysTeken)
            .then((result) => {
                let dataBalance = result.data.Balance;

                this.props.balance(dataBalance.Balance);
                this.setState({
                    balance: dataBalance.Balance,
                    currency: dataBalance.Currency,
                    refreshing: false,
                    isFirstLoading: false,
                });

            })
            .catch((error) => {
                console.log('SelectBankCardModal--componentDidMount-error: ', error);
                this.loaded()

            })
    }


    /*获取借记卡*/
    getDebitCardInfo(userId) {
        this.iparNetwork.getRequest(SERVER_TYPE.synPays + 'DebitCard?', 'Auth=' + getSynPaysSellerAuth(this.props.country, 1) + '&UserID=' + userId)
            .then((result) => {
                if (result.ApiResponseCode === 200) {
                    for (let i = 0; i < result.data.length; i++) {
                        this.bankCard.push(result.data[i]);
                    }

                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(this.bankCard),
                        refreshing: false,
                        isFirstLoading: false,
                    })
                } else {
                    this.loaded()

                }
            })
            .catch((error) => {
                this.loaded();

                console.log(error);
            });


    }

    loaded() {
        this.setState({
            refreshing: false,
            isFirstLoading: false,
        })
    }

    /*获取信用卡*/
    getCreditCardInfo(userId) {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCardInfo?', 'UserID=' + userId + "&Type=CreditCard")

            .then((result) => {

                if (result.code === 200) {
                    this.setState({
                        refreshing: false,
                        isFirstLoading: false,
                        dataSource: ds.cloneWithRows(result.data)
                    })
                } else {
                    this.loaded()
                }
            })
            .catch((error) => {
                this.loaded();

                console.log(error);
            })


    }


    /**
     * 刷新props
     * @param nexProps
     */
    componentWillReceiveProps(nexProps) {
        if (this.state.visible !== nexProps.visible) {
            this.setState({
                visible: nexProps.visible,
                userId: nexProps.userId,
            });
            if (nexProps.userId && (nexProps.isFirstLoading || this.state.isFirstLoading)) {
                this.props.updateLoadingStatus && this.props.updateLoadingStatus();
                this.onLoadData(nexProps.userId);
            }
        }
    }


    render() {
        return (
            <Modal
                onRequestClose={() => this.props.onClose()}
                animationType={'slide'}
                transparent={true}
                visible={this.state.visible}
            >

                <View style={styles.boxStyle}>

                    <View style={[styles.minBox]}>

                        <View style={[StyleUtils.rowDirection, StyleUtils.center, {padding: 16}]}>
                            <Text style={[StyleUtils.flex, StyleUtils.smallFont, {
                                fontSize: 17,
                                color: 'black',
                                textAlign: 'left'
                            }]}>
                                {I18n.t('default.selectPayment')}
                            </Text>


                            <TouchableOpacity
                                onPress={() => this.props.onClose()}>
                                <Text
                                    style={[styles.closeTv, StyleUtils.smallFont]}>
                                    {I18n.t('default.close')}
                                </Text>
                            </TouchableOpacity>
                        </View>

                        {/*<TouchableHighlight*/}
                        {/*style={[StyleUtils.center, {height: 40, width: 40}]}*/}
                        {/*onPress={() => this.props.onClose()}*/}
                        {/*underlayColor={'#e3e3e3'}*/}
                        {/*>*/}
                        {/*<Image style={[StyleUtils.tabIconSize]}*/}
                        {/*source={require('../../res/images/ic_close.png')}/>*/}

                        {/*</TouchableHighlight>*/}
                        {/*PLEASE CHOOSE THE WAY OF PAYMENT*/}
                        {/*<Text*/}
                        {/*style={[styles.text, StyleUtils.smallFont, {marginTop: 16}]}>{}</Text>*/}

                        <View style={StyleUtils.lineStyle}/>

                        <ScrollView
                            refreshControl={
                                <RefreshControl
                                    refreshing={this.state.refreshing}
                                />
                            }
                            style={{margin: 16, paddingTop: 0}}>

                            {this.renderItem(I18n.t('default.balance') + ' ( ' + this.state.balance + this.state.currency + ' )',
                                require('../../res/images/ic_synpays.jpg'), () => this.onItemClick())}


                            <ListView
                                dataSource={this.state.dataSource}
                                renderRow={(rowData, sectionID, rowID) => this.renderRow(rowData, rowID)}
                            />

                            {this.renderItem(I18n.t('default.addNewCard'),
                                require('../../res/images/ic_add.png'),
                                () => this.onItemClick('add'), {width: 16, height: 16, margin: 8})}

                        </ScrollView>

                        <View style={{padding: 16, paddingBottom: 30}}>
                            {ViewUtils.getButton(I18n.t('default.payNow'), () => this.props.onItemClick('payNow'))}
                        </View>
                    </View>

                </View>
            </Modal>
        )
    }


    onItemClick(rowData) {
        this.props.onItemClick(rowData);
    }


    /**
     *renderItem
     * @returns {*}
     */
    renderItem(text, img, callback, iconStyle) {
        return <TouchableHighlight
            onPress={callback}
            underlayColor={'#dcdcdc'}
            style={{marginTop: 16}}

        >
            <View style={[StyleUtils.rowDirection, styles.item]}>
                <Image
                    style={[styles.icon, iconStyle]}
                    source={img}/>

                <Text style={[styles.text, StyleUtils.smallFont]}>
                    {text}
                </Text>
            </View>
        </TouchableHighlight>
    }

    /**
     * listView 的 item
     * @param rowData
     * @param rowID
     * @returns {*}
     */
    renderRow(rowData, rowID) {
        return this.renderItem(rowData.CardNumber,
            require('../../res/images/ic_bank_card.png'), () => this.onItemClick(rowData));
    }
}
const styles = StyleSheet.create({

    btnBox: {
        padding: 16,
        paddingTop: 0,
        backgroundColor: 'rgba(255, 255, 255, 0.88)',
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0
    },
    boxStyle: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',

    },
    minBox: {
        height: 400,
        backgroundColor: 'white',
    },
    text: {
        fontSize: 16,
        paddingLeft: 16,
    },
    icon: {
        width: 34,
        height: 34,
    },
    item: {
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#d4d5d6',
        padding: 8,
    }
});
